# -*- coding: utf-8 -*-
from flask import Flask, request, send_file
from flask_cors import CORS
import os
from oss import OSSUploader
from datetime import datetime
from chat import ChatBot
from tts import TestTts
from asr import ASR
from shared import logging

# 初始化日志
logger = logging.getLogger(__name__)

app = Flask(__name__)
CORS(app)

# 初始化 ChatBot
chatbot = ChatBot()

# 确保上传目录存在
UPLOAD_FOLDER = os.path.join(os.path.dirname(__file__), 'uploads')
if not os.path.exists(UPLOAD_FOLDER):
    os.makedirs(UPLOAD_FOLDER)

# 创建 OSS 上传器实例
oss_uploader = OSSUploader()

@app.route('/api/speech-to-text', methods=['POST'])
def speech_to_text():
    logger.debug('开始处理语音转文字请求')
    logger.debug(f'请求参数: {request.files}')
    if 'audio' not in request.files:
        logger.error('请求中未找到音频文件')
        return {'error': '没有找到音频文件'}, 400
    
    audio_file = request.files['audio']
    if audio_file.filename == '':
        logger.error('未选择文件')
        return {'error': '没有选择文件'}, 400

    current_time = datetime.now().strftime('%Y%m%d_%H%M%S_%f')
    filename = f'audio_{current_time}.wav'
    file_path = os.path.join(UPLOAD_FOLDER, filename)
    logger.debug(f'准备保存音频文件: {file_path}')
    
    try:
        audio_file.save(file_path)
        logger.debug('音频文件已保存到本地')
        
        oss_path = f'audio/{filename}'
        logger.debug(f'OSS上传参数 - 本地文件: {file_path}, OSS路径: {oss_path}')
        oss_url = oss_uploader.upload_file(file_path, oss_path)
        logger.debug(f'OSS上传返回: {oss_url}')
        
        if not oss_url:
            logger.error('OSS 上传失败')
            return {'error': '上传到 OSS 失败'}, 500

        logger.debug(f'ASR请求参数 - 音频URL: {oss_url}')
        asr_result = ASR.transcribe(oss_url)
        logger.debug(f'ASR返回结果: {asr_result}')
        if not asr_result:
            logger.error('语音识别失败')
            return {'error': '语音识别失败'}, 500

        text = asr_result['Sentences'][0]['Text'] if asr_result.get('Sentences') else ''
        logger.debug(f'语音识别结果: {text}')

        # if os.path.exists(file_path):
        #     os.remove(file_path)
        #     logger.debug('已删除本地临时文件')

        response_data = {
            'message': '音频文件上传成功',
            'filename': filename,
            'url': oss_url,
            'text': text
        }
        logger.debug(f'API返回结果: {response_data}')
        return response_data, 200
        
    except Exception as e:
        logger.error(f'处理文件时出错: {str(e)}', exc_info=True)
        if os.path.exists(file_path):
            os.remove(file_path)
            logger.debug('错误处理：已删除本地临时文件')
        return {'error': f'处理文件时出错: {str(e)}'}, 500

@app.route('/api/chat', methods=['POST'])
def chat():
    logger.debug('开始处理聊天请求')
    data = request.get_json()
    logger.debug(f'请求参数: {data}')

    logger.debug(f'ChatBot请求参数: {data["message"]}')
    reply = chatbot.chat(data['message'])
    logger.debug(f'ChatBot返回结果: {reply}')

    response_data = {'reply': reply}
    logger.debug(f'API返回结果: {response_data}')
    return response_data, 200

@app.route('/api/text-to-speech', methods=['POST'])
def text_to_speech():
    logger.debug('开始处理文字转语音请求')
    data = request.get_json()
    logger.debug(f'请求参数: {data}')

    try:
        logger.debug(f'TTS请求参数: {data["text"]}')
        audio_file = TestTts.synthesize_text(data['text'])
        logger.debug(f'TTS返回音频文件路径: {audio_file}')
        
        return send_file(
            audio_file,
            mimetype='audio/mp3',
            as_attachment=True,
            download_name='speech.mp3'
        )
    except Exception as e:
        logger.error(f'语音合成失败: {str(e)}', exc_info=True)
        return {'error': f'语音合成失败: {str(e)}'}, 500

if __name__ == '__main__':
    app.run(debug=True, port=5000)